<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Cache;

class Order extends Base
{
    protected $name = 'order';

    protected $type = [
        'pay_time' => 'timestamp',
        'remind_time' => 'timestamp',
        'post_time' => 'timestamp',
        'receipt_time' => 'timestamp',
        'comment_time' => 'timestamp',
        'finish_time' => 'timestamp',
        'refund_time' => 'timestamp',
        'cancel_time' => 'timestamp'
    ];

    protected function orderType(): object
    {
        return $this->hasOne(ProductType::class, 'id', 'order_type')
            ->field('id,title');
    }

    protected function user(): object
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,photo');
    }

    protected function p(): object
    {
        return $this->hasOne(Area::class, 'id', 'province')
            ->field('id,ext_name as title');
    }

    protected function c(): object
    {
        return $this->hasOne(Area::class, 'id', 'city')
            ->field('id,ext_name as title');
    }

    protected function d(): object
    {
        return $this->hasOne(Area::class, 'id', 'district')
            ->field('id,ext_name as title');
    }

    protected function express(): object
    {
        return $this->hasOne(Express::class, 'id', 'express_id')
            ->field('id,title,code');
    }

    protected function productsField(): object
    {
        return $this->hasMany(OrderProduct::class, 'order_id')
            ->field('id,order_id,uid,pid,type_id,title,spec,icon,num,vip_price,amount,freight');
    }

    protected function getPayWayAttr($value): string
    {
        return get_pay_way($value);
    }

    protected function getStatusNameAttr($value, $data): string
    {
        return getOrderStatus($data['status']);
    }

    public static function deliver($param, $admin): array
    {
        try {
            $info = parent::where(['id' => $param['id']])->find();
            if (empty($info)) {
                throw new \Exception('该订单不存在');
            }
            $day = Cache::get('system')['auto_receipt_day'];
            $status = $info->status;
            $info->receiver = $param['receiver'];
            $info->receiver_tel = $param['receiver_tel'];
            $info->province = $param['province'];
            $info->city = $param['city'];
            $info->district = $param['district'];
            $info->address_details = $param['address_details'];
            $info->post_mobile = !empty($param['post_mobile']) ? $param['post_mobile'] : '';
            $info->express_id = $param['express_id'];
            $info->express_code = $param['express_code'];
            $info->post_remark = $param['post_remark'];
            $info->post_time = time();
            $info->auto_receipt_time = strtotime(date("Y-m-d", strtotime("+" . $day . " day")));
            if ($status == 2) {
                $info->status = 3;
            }
            $res = $info->save();
            if ($res !== true) {
                throw new \Exception('发货失败');
            }
            if ($status == 2) {
                $content = '订单发货，订单号【' . $info->sn . '】下单会员【' . $info->user->code . '】';
                $msg = '发货成功';
                $notify = "您的订单【{$info->sn}】发货成功，请等待收货";
                UserNotify::add(2, $info->uid, '订单发货', $notify, $info->id);
            } else {
                $content = '修改了订单发货信息，订单号【' . $info->sn . '】下单会员【' . $info->user->code . '】';
                $msg = '修改成功';
                $notify = "您的订单【{$info->sn}】修改发货信息，请注意查收";
                UserNotify::add(2, $info->uid, '订单发货', $notify, $info->id);
            }
            Logs::adds($content, $admin->id, $admin->admin_name);

        } catch (\Exception $e) {

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => $msg];
    }

    public static function importDeliver($file, $admin): array
    {
        parent::startTrans();
        try {
            $file = '.' . $file;
            $file_type = \PhpOffice\PhpSpreadsheet\IOFactory::identify($file);
            $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($file_type);
            $spreadsheet = $reader->load($file);
            $sheet = $spreadsheet->getActiveSheet();
            $data = $sheet->toArray();
            if (empty($data)) {
                throw new \Exception('导入失败，请检查数据和格式是否正确');
            }
            foreach ($data as $key => $val) {
                $line = $key + 1;
                if ($key > 0 && !empty($val[0])) {
                    [$id, $sn, $post_mobile, $delivery_id, $express_name, $express_code] = explode(',', implode(',', $val));
                    if (empty($id)) continue;
                    if (empty($express_name) && empty($delivery_id)) continue;
                    if (empty($express_code)) continue;
                    $order = parent::where(['sn' => trim($sn), 'status' => 2])->find();
                    if (empty($order)) continue;
                    $map = !empty($delivery_id) ? ['code' => trim($delivery_id)] : ['title' => trim($express_name)];
                    $express = Express::where($map)->field('id,title')->find();
                    if (empty($express)) {
                        throw new \Exception("导入失败：表格第【{$line}行】物流公司或物流编码输入错误，非系统内录入数据");
                    }
                    $res = self::deliver([
                        'id' => $id,
                        'post_mobile' => $post_mobile,
                        'express_id' => $express->id,
                        'express_code' => trim($express_code),
                        'receiver' => $order->receiver,
                        'receiver_tel' => $order->receiver_tel,
                        'province' => $order->province,
                        'city' => $order->city,
                        'district' => $order->district,
                        'address_details' => $order->address_details,
                        'post_remark' => '导入发货'
                    ], $admin);
                    if ($res['code'] != 1) {
                        throw new \Exception("导入失败，表格第【{$line}行】处理发货失败");
                    }
                }
            }

            unlink($file);
            parent::commit();
        } catch (\Exception $e) {
            unlink($file);
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => '批量发货成功'];
    }
}